﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Gma.System.MouseKeyHook;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Threading;
namespace stopwatch;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    volatile int num = 0;
    volatile bool running = false;
    object valueTypeLock = new object();
    public MainWindow()
    {
        InitializeComponent();
    }
    private System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();


    private void Invoke(Action act)
    {
        this.Dispatcher.BeginInvoke(DispatcherPriority.Send, act);
    }

    private void Window_Loaded(object? sender, RoutedEventArgs e)
    {
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
        dispatcherTimer.Start();
        Subscribe();
        double x1 = SystemParameters.PrimaryScreenWidth;
        this.Left = x1 - this.ActualWidth;

    }
    private void Window_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
    {
        Unsubscribe();
    }

    private void dispatcherTimer_Tick(object? sender, EventArgs e)
    {
        if (running)
        {
            Invoke(() =>
            {
                txtNum.Text = (++num).ToString();
            });

        }

    }


    private IKeyboardMouseEvents m_GlobalHook = Hook.GlobalEvents();

    public void Subscribe()
    {
        m_GlobalHook.KeyDown += OnKeyDown;
    }
    SolidColorBrush gray = System.Windows.Media.Brushes.Gray;
    SolidColorBrush green = System.Windows.Media.Brushes.Green;
    private void StartOrStop()
    {
        lock (valueTypeLock)
        {
            if (running)
            {
                running = false;
                txtNum.Opacity = 1;
                txtNum.Stroke = gray;
            }
            else
            {
                running = true;
                num = -1;
                txtNum.Stroke = green;
                txtNum.Opacity = 0.5;
            }
        }

        Visibility = Visibility.Visible;
    }

    private void OnKeyDown(object? sender, System.Windows.Forms.KeyEventArgs e)
    {
        // Console.WriteLine(string.Format("KeyDown  \t\t {0}\n", e.KeyCode));
        if (e.KeyCode == Keys.LControlKey || e.KeyCode == Keys.RControlKey)
        {
            StartOrStop();
        }
        else if (e.KeyCode == Keys.X)
        {
            Visibility = Visibility.Hidden;

        }

    }

    public void Unsubscribe()
    {
        m_GlobalHook.KeyDown -= OnKeyDown;
        m_GlobalHook.Dispose();
    }
}